package me.macd.mindoc.service.impl;

import me.macd.mindoc.controller.Common;
import me.macd.mindoc.dao.BookDao;
import me.macd.mindoc.dao.DocumentDao;
import me.macd.mindoc.dao.MemberDao;
import me.macd.mindoc.dao.RelationshipDao;
import me.macd.mindoc.model.*;
import me.macd.mindoc.service.BookService;
import me.macd.mindoc.util.Page;
import me.macd.mindoc.util.constants.BookRole;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @program: mindoc
 * @description: ${description}
 * @author: 2018-09-22
 * @create: 2018-09-22 11:47
 */
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    BookDao bookDao;

    @Autowired
    DocumentDao documentDao;

    @Autowired
    RelationshipDao relationshipDao;

    @Autowired
    MemberDao memberDao;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Page<BookResult> findForHomeToPager(int pageIndex, int pageSize, int memberId) {
        int offset = (pageIndex - 1) * pageSize;

        Page<BookResult> page = new Page<>();
        page.setTotalCount(bookDao.countForHomeToPager(memberId));
        page.setItems(bookDao.findForHomeToPager(offset, pageSize, memberId));
        return page;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Page<BookResult> findToPager(int pageIndex, int pageSize, int memberId) {
        int offset = (pageIndex - 1) * pageSize;

        Page<BookResult> page = new Page<>();
        page.setTotalCount(bookDao.countToPager(memberId));
        List<BookResult> list = bookDao.findToPager(offset, pageSize, memberId);

        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = documentDao.modifyInfo(list.get(i).getBookId());
            Date date = (Date) map.get("modify_time");
            LocalDateTime dateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String account = map.get("account") == null ? "未知" : map.get("account").toString();
            String info = account + " 于 " + dtf.format(dateTime);
            list.get(i).setLastModifyText(info);

            int roleId = list.get(i).getRoleId();
            list.get(i).setRoleName(BookRole.valueOf(roleId).text());
        }

        page.setItems(list);

        return page;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public BookResult findByIdentify(String identify, int memberId) {
        List<Books> books = bookDao.findListByIdentify(identify, memberId);
        if (books.size() == 0) {
            return new BookResult();
        }
        Books book = books.get(0);

        List<Relationship> relationships = relationshipDao.findListByBookId(book.getBookId(), memberId);
        if (relationships.size() == 0) {
            return new BookResult();
        }
        Relationship relationship = relationships.get(0);

        List<Relationship> relationships2 = relationshipDao.findListByBookIdAndRoleId(book.getBookId(), 0);
        if (relationships2.size() == 0) {
            return new BookResult();
        }
        Relationship relationship2 = relationships2.get(0);

        Members member = memberDao.findByPrimaryKey(relationship2.getMemberId());

        BookResult bookResult = toBookResult(book);
        bookResult.setCreateName(member.getAccount());
        if (!StringUtils.isBlank(member.getRealName())) {
            bookResult.setRealName(member.getRealName());
        }
        bookResult.setMemberId(relationship.getMemberId());
        bookResult.setRoleId(relationship.getRoleId());
        bookResult.setRelationshipId(relationship.getRelationshipId());
        bookResult.setRoleName(BookRole.valueOf(bookResult.getRoleId()).text());

        return bookResult;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean existByIdentify(String identify) {
        return bookDao.countByIdentify(identify) > 0;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insert(Books books) {
        int key = bookDao.insert(books);
        books.setBookId(key);
        Relationship relationship = new Relationship();
        relationship.setBookId(books.getBookId());
        relationship.setRoleId(0);
        relationship.setMemberId(Common.memberId());
        relationshipDao.insert(relationship);
        DocumentsWithBLOBs document = new DocumentsWithBLOBs();
        document.setBookId(books.getBookId());
        document.setDocumentName("空白文档");
        document.setMemberId(Common.memberId());
        document.setCreateTime(new Date());
        document.setModifyTime(new Date());
        documentDao.insert(document);
        return 1;
    }

    private BookResult toBookResult(Books book) {
        BookResult bookResult = new BookResult();
        bookResult.setBookId(book.getBookId());
        bookResult.setBookName(book.getBookName());
        bookResult.setIdentify(book.getIdentify());
        bookResult.setOrderIndex(book.getOrderIndex());
        bookResult.setDescription(book.getDescription());
        bookResult.setPrivatelyOwned(book.getPrivatelyOwned());
        bookResult.setPrivateToken(book.getPrivateToken());
        bookResult.setDocCount(book.getDocCount());
        bookResult.setCommentStatus(book.getCommentStatus());
        bookResult.setCommentCount(book.getCommentCount());
        bookResult.setCreateTime(book.getCreateTime());
        bookResult.setModifyTime(book.getModifyTime());
        bookResult.setCover(book.getCover());
        bookResult.setLabel(book.getLabel());
        bookResult.setStatus(book.getStatus());
        bookResult.setEditor(book.getEditor());
        bookResult.setTheme(book.getTheme());
        bookResult.setAutoRelease(book.getAutoRelease());
        bookResult.setIsEnableShare(book.getIsEnableShare());
        bookResult.setIsUseFirstDocument(book.getIsUseFirstDocument());
        bookResult.setPublisher(book.getPublisher());
        bookResult.setHistoryCount(book.getHistoryCount());
        bookResult.setIsDownload(book.getIsDownload());
        bookResult.setAutoSave(book.getAutoSave());

        if (StringUtils.isBlank(book.getTheme())) {
            bookResult.setTheme("default");
        }
        if (StringUtils.isBlank(book.getEditor())) {
            bookResult.setEditor("markdown");
        }

        Map<String, Object> map = documentDao.modifyInfo(book.getBookId());
        Date date = (Date) map.get("modify_time");
        LocalDateTime dateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String account = map.get("account") == null ? "未知" : map.get("account").toString();
        String info = account + " 于 " + dtf.format(dateTime);
        bookResult.setLastModifyText(info);

        return bookResult;
    }
}
